<template>
  <a-tree-select
    v-model="deptId"
    v-bind="attrs"
    :labelInValue="false"
    allowClear
    show-search
    :tree-data="dataSource"
    :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
    :getPopupContainer="(node) => node.parentNode"
    :replaceFields="replaceFields"
    treeNodeFilterProp="title"
  >
  </a-tree-select>
</template>

<script>

import { TreeSelect as ATreeSelect } from 'ant-design-vue'
import { deptTree } from '@/services/system'
export default {
  name: 'ZSelectDept',
  components: { ATreeSelect },
  props: ['value'],
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      replaceFields: {
        children: 'children',
        title: 'deptName',
        value: 'deptCode'
      },
      dataSource: [],
      default: {
        maxTagCount: 2,
        treeCheckStrictly: true
      }
    }
  },
  computed: {
    attrs() {
      return Object.assign(this.default, this.$attrs)
    },
    deptId: {
      get() { // 处理数据格式为tree 多选需要的格式[{lable:'部门',value:"bm-01"}]
        let deptId
        if (this.value instanceof Array) {
          deptId = []
          this.value.forEach(item => {
            deptId.push({
              value: item
            })
          })
        } else {
          deptId = this.value
        }
        return deptId
      },
      set(value) { // 将数据转换为[id1,id2]格式
        let deptId
        if (value instanceof Array) {
          deptId = []
          value.forEach(item => {
            deptId.push(item.value)
          })
        } else {
          deptId = value
        }
        this.$emit('change', deptId)
      }
    }
  },
  methods: {
    loadData() {
      deptTree().then((res) => {
        if (res.success) {
          this.dataSource = res.result
        } else {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>
